<template>
  <div class="app">
    <div class="left">
      <div v-for="item in components" :key="item.title" class="components-item" @click="handleAddComp(item)">{{ item.title
      }}
      </div>
    </div>
    <div class="center">
      <div class="page">
        <Vue3DraggableResizable v-for="(item, index) in pageSchema" :key="item.id" :parent="true"
          :lock-aspect-ratio="true" :handles="['tl', 'tr', 'br', 'bl']" :x="item.props.style.left"
          :y="item.props.style.top" :w="item.props.style.width" :h="item.props.style.height" class="drag_box"
          @activated="activatedHandle(index)" @dragging="handleDrag($event, index)"
          @resizing="handleResize($event, index)">
          <component :is="item.name" v-bind="item.props"></component>
        </Vue3DraggableResizable>
      </div>
    </div>
    <div class="right">
      <div v-if="pageSchema[activeIndex]">
        <PropertyRender :properties="pageSchema[activeIndex].props" @change="handleChange" />
      </div>

    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useStore } from 'vuex'
import PropertyRender from './components/PropertyRender.vue'
const store = useStore()
const { components } = store.state
const pageSchema = reactive([])
const activeIndex = ref(null)

const handleAddComp = (item) => {
  pageSchema.push({ ...item, id: new Date().getTime() })
}
const activatedHandle = (index) => {
  activeIndex.value = index
}

// 搭投
const handleDrag = (options, index) => {
  pageSchema[index].props.style.left = options.x
  pageSchema[index].props.style.top = options.y
}
const handleResize = (options, index) => {
  pageSchema[index].props.style.left = options.x
  pageSchema[index].props.style.top = options.y
  pageSchema[index].props.style.width = options.w
  pageSchema[index].props.style.height = options.h
}

// 子传父核心
// 1. 在父组件中，将方法传递给子组件
// 2. 子组件调用传递的方法（vue，emit;小程序 triggerEvenet;react props.xxx()）
// 3. 传递参数
const handleChange = (value, key) => {
  console.log('event 触发')
  console.log(key, value)
  function setValue(obj) {
    for (const prop in obj) {
      if (prop === key) {
        obj[prop] = value
      } else if (typeof obj[prop] === 'object' && obj[prop]) {
        setValue(obj[prop])
      }
    }
  }
  setValue(pageSchema[activeIndex.value].props)
  // [key] = value
}
</script>

<style lang="scss">
body {
  margin: 0;
}

.app {
  display: flex;
  background-color: #e5e5e5;
  min-height: 100vh;
  justify-content: space-between;
}

.left {
  width: 260px;
  background-color: #fff;
}

.center {
  width: 800px;
  margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  width: 400px;
  background-color: #fff;
}

.page {
  width: 375px;
  height: 680px;
  background-color: #fff;
  position: relative;
}

.components-item {
  height: 60px;
  font-size: 26px;
  line-height: 60px;
  cursor: pointer;
}
</style>
